package com.yanqu.road.web.controller.usercenter.newadmin;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossUnionServerGroupDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.entity.web.ICrossWebService;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.CrossServerType;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 18.妖盟管理
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CenterAdminUnionController {

    private static Logger logger = LogManager.getLogger(CenterAdminUnionController.class.getName());

    /**
     * 18.1 修改
     */
    @ResponseBody
    @RequestMapping(value = "union/modify", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String modifyUnion(HttpServletRequest request, @RequestBody JSONObject jsonObject) {


        int channelId = jsonObject.getIntValue("channelId");
        long serverId = jsonObject.getLongValue("serverId");
        String unionUid = jsonObject.getString("monsterLeagueId");
        String unionName = jsonObject.getString("monsterLeagueName");
        int joinLimit = jsonObject.getIntValue("joinLimit");
        int level = jsonObject.getIntValue("level");

        String notice = jsonObject.getString("notice");
        String declaration = jsonObject.getString("declaration");
        String leaderWechat = jsonObject.getString("leaderWechat");

        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);

        JSONObject param = new JSONObject();

        param.put("unionUid", unionUid);
        param.put("unionName", unionName);
        param.put("outNotice", notice);
        param.put("innerNotice", declaration);
//        param.put("qqCode", "");
        param.put("wechatCode", leaderWechat);
//        param.put("joinLimit", joinLimit);
//        param.put("level", level);

        String op = "AgentUnion|changeUnionInfo";
        JSONObject callParam = new JSONObject();
        callParam.put("op", op);
        callParam.put("param",param);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("param", callParam.toJSONString());

        String response = HttpHelper.doPost(serverInfo.getWebServerUrl() + "/adminOperate", paramMap, "UTF-8");
        if(!StringUtils.isNullOrEmpty(response)){
            JSONObject parseObject = JSONObject.parseObject(response);
            if(parseObject.containsKey("status") && parseObject.getIntValue("status") == 1){
                return AdminResult.defaultInstance().toJsonString();
            }
        }
        return AdminResult.failMsg("").toJsonString();
    }


    /**
     * 18.2 查询
     */
    @ResponseBody
    @RequestMapping(value = "union/search", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchUnion(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        long serverId = 0;

        if(jsonObject.containsKey("serverId")){
            serverId = jsonObject.getLongValue("serverId");
        }

        if(serverId > 0) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);

            String response = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/game/admin/union/search", jsonObject.toJSONString(), "UTF-8");
            if (StringUtils.isNullOrEmpty(response)) {
                return AdminResult.failMsg("网络失败").toJsonString();
            }
            if (HttpHelper.ERROR.equals(response)) {
                return AdminResult.failMsg("网络失败").toJsonString();
            }

            return response;

        }else {

            List<ProcessInfo> processInfoList = new ArrayList<>();
            List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
            serverInfoList.removeIf(next -> next.getCrossServerType() != CrossServerType.RANK_CROSS_2);

            for (CrossServerInfo crossServerInfo : serverInfoList) {
                if(Config.isDebug() && crossServerInfo.getCrossServerId() != 99900177){
                    continue;
                }

                for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                    if(processInfo.getServerName().equals("cross_server")) {
                        processInfoList.add(processInfo);
                    }
                }
            }
            ProcessInfo processInfo = processInfoList.get(0);

            try {
                //直接向商会跨服查询
                String url = "http://" + processInfo.getAddress() + ":" + processInfo.getAdminPort() + "/crossws?wsdl";
                QName qName = new QName("http://webservice.server.road.yanqu.com/", "GrossWebServiceService");
                Service service = Service.create(new URL(url), qName);
                ICrossWebService crossWebService = service.getPort(ICrossWebService.class);
                String resp = crossWebService.executeAdminOperate("AgentUnion|unionSearch", jsonObject.toJSONString(), "Yanqu123");
                JSONObject result = JSONObject.parseObject(resp);
                int status = result.getInteger("status");
                if (status == 1) {
                    return result.getString("result");
                }else {

                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }

        }

        return AdminResult.failMsg("").toJsonString();
    }


    /**
     * 18.3 妖盟成员列表
     */
    @ResponseBody
    @RequestMapping(value = "union/memberList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String memberList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        long serverId = 0;
        if(jsonObject.containsKey("serverId")){
            serverId = jsonObject.getLongValue("serverId");
        }


        if(serverId > 0) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);

            String response = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/game/admin/union/memberList", jsonObject.toJSONString(), "UTF-8");
            if (StringUtils.isNullOrEmpty(response)) {
                return AdminResult.failMsg("网络失败").toJsonString();
            }
            if (HttpHelper.ERROR.equals(response)) {
                return AdminResult.failMsg("网络失败").toJsonString();
            }

            return response;

        }else {

            List<ProcessInfo> processInfoList = new ArrayList<>();
            List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
            serverInfoList.removeIf(next -> next.getCrossServerType() != CrossServerType.RANK_CROSS_2);

            for (CrossServerInfo crossServerInfo : serverInfoList) {
                if (Config.isDebug() && crossServerInfo.getCrossServerId() != 99900177) {
                    continue;
                }

                for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                    if (processInfo.getServerName().equals("cross_server")) {
                        processInfoList.add(processInfo);
                    }
                }
            }
            ProcessInfo processInfo = processInfoList.get(0);

            try {
                //直接向商会跨服查询
                String url = "http://" + processInfo.getAddress() + ":" + processInfo.getAdminPort() + "/crossws?wsdl";
                QName qName = new QName("http://webservice.server.road.yanqu.com/", "GrossWebServiceService");
                Service service = Service.create(new URL(url), qName);
                ICrossWebService crossWebService = service.getPort(ICrossWebService.class);
                String resp = crossWebService.executeAdminOperate("AgentUnion|unionMember", jsonObject.toJSONString(), "Yanqu123");
                JSONObject result = JSONObject.parseObject(resp);
                int status = result.getInteger("status");
                if (status == 1) {
                    return result.getString("result");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }


    /**
     * 18.4 盟主转移
     */
    @ResponseBody
    @RequestMapping(value = "union/transferUnion", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String transferUnion(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        long serverId = 0;
        if(jsonObject.containsKey("serverId")){
            serverId = jsonObject.getLongValue("serverId");
        }

        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);

        String response = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/game/admin/union/transferUnion", jsonObject.toJSONString(), "UTF-8");
        if (StringUtils.isNullOrEmpty(response)) {
            return AdminResult.failMsg("网络失败").toJsonString();
        }
        if (HttpHelper.ERROR.equals(response)) {
            return AdminResult.failMsg("网络失败").toJsonString();
        }

        return response;

    }

    /**
     * 15.1 跨服商会分组查询
     */
    @ResponseBody
    @RequestMapping(value = "server/getUnionGroupInfo", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getUnionGroupInfo(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");

        if(channelId == 0){
            return AdminResult.failMsg("渠道参数不对").toJsonString();
        }

        Map<Integer, CrossUnionServerGroup> serverGroupMap = new CrossUnionServerGroupDaoImpl().getServerGroupMap(channelId);

        eChannelType channelType = eChannelType.forValue(channelId);
        AdminResult2 result2 = AdminResult2.defaultInstance();
        for (Map.Entry<Integer, CrossUnionServerGroup> groupEntry : serverGroupMap.entrySet()) {
            CrossUnionServerGroup group = groupEntry.getValue();
            JSONObject object = new JSONObject();
            object.put("channelId", group.getChannelId());
            object.put("groupId", group.getGroupId());
            object.put("channelName", channelType.getName());
            object.put("serverIds", StringUtils.listToString(group.getServerList(), ","));
            result2.getData().add(object);
        }

        return result2.toJsonString();
    }

    /**
     * 15.2 轮次对应区服列表
     */
    @ResponseBody
    @RequestMapping(value = "server/getServerRound", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getServerRound(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        long time = jsonObject.getLongValue("time");

        if(channelId == 0 || time == 0){
            return AdminResult.failMsg("参数不对").toJsonString();
        }

        List<ServerInfo> serverList = ServerListMgr.getChannelServerList(channelId);
        Map<String, List<Long>> result = new HashMap<>();

        for (ServerInfo serverInfo : serverList) {
            int turn = ServerListMgr.getServerTurn(serverInfo, time);
            String key = String.valueOf(turn);
            if(!result.containsKey(key)){
                result.put(key, new ArrayList<>());
            }
            result.get(key).add(serverInfo.getServerId());
        }

        AdminResult adminResul = AdminResult.defaultInstance();

        adminResul.getData().putAll(result);

        return adminResul.toJsonString();

    }
}
